package task;

import model.ObjectLock;

/**
 * 对象锁任务
 *
 * @author wxhntmy
 */
public class ObjectLockTask implements Runnable {

    /**
     * 任务名称
     */
    private String name;

    /**
     * 共享对象
     */
    private ObjectLock objectLock;

    /**
     * 构造函数
     *
     * @param name       任务名称
     * @param objectLock 线程共享对象
     */
    public ObjectLockTask(String name, ObjectLock objectLock) {
        this.name = name;
        this.objectLock = objectLock;
    }

    @Override
    public void run() {
        //System.out.println(this.toString() + " is running!");

        synchronized (objectLock) {
            for (int i = 1; i < 6; i++) {
                objectLock.setCounter(objectLock.getCounter() + i);
                System.out.println(this.getName() + " counter: " + objectLock.getCounter());
            }
        }

        //System.out.println(this.toString() + " is end!");
    }

    /**
     * 获取任务名称
     *
     * @return 任务名称
     */
    public String getName() {
        return name;
    }

    @Override
    public String toString() {
        return "MyTask [ name = " + name + " ]";
    }
}